package com.example.studyPlatform.controller;

import com.example.studyPlatform.bean.Post;
import com.example.studyPlatform.bean.User;
import com.example.studyPlatform.config.ThemeConfig;
import com.example.studyPlatform.controller.api.ContentApi;
import com.example.studyPlatform.mapper.PostMapper;
import com.example.studyPlatform.mapper.UserMapper;
import com.example.studyPlatform.service.protocol.PostService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

import static com.example.studyPlatform.config.BaseConstant.*;
import static com.example.studyPlatform.config.RoutingConstant.*;

@Controller
@AllArgsConstructor
public class ContentController {

    ThemeConfig themeConfig;
    PostService postService;
    ContentApi contentApi;
    UserMapper userMapper;
    PostMapper postMapper;

    final String POST_KEY = "post";
    final String AUTHOR_KEY = "author";


    @GetMapping(USER + "/publish")
    String publish(String content) {
        return themeConfig.render(USER + "/publish");
    }

    @PostMapping(value = ARTICLE + "/post")
    String postContent(int type, boolean disallowComment, String title, String summary, String thumbnail, String content, HttpSession session, Model model) {
        User user = (User) session.getAttribute(USR);
        postService.publish(type, user.getId(), disallowComment, title, summary, thumbnail, content);
        model.addAttribute("msg", "发布成功");
        return themeConfig.render(USER + "/publish");
    }

    @GetMapping(value = PUBLIC_PATH + ARTICLE + "/{id:[0-9]+}")
    String renderArticle(@PathVariable("id") int id, HttpSession session, Model model) throws Exception {
        Post post = contentApi.content(id);
        model.addAttribute(POST_KEY, post);
        // 找出作者
        User author = userMapper.getUserById(postMapper.getPostById(id).getAuthor());
        author.setPassword(null);
        model.addAttribute(AUTHOR_KEY, author);
        return themeConfig.render(PUBLIC_PATH + ARTICLE);
    }

    @GetMapping("/random/image")
    String randomImage() {
        return REDIRECT + "https://api.lixingyong.com/api/images?type=url&itype=image&postid=" + random();
    }

    int random() {
        return (int) ((2 * Math.random() - 1) * Integer.MAX_VALUE);
    }

    @GetMapping(API_PATH + "/del/{id}")
    String delPost(Model model) {
        model.addAttribute(MSG, "删除成功");

        return themeConfig.render(USER);
    }

    ;

}
